# core/main.py
from fastapi import FastAPI, HTTPException
from fastapi.responses import StreamingResponse
from fastapi.staticfiles import StaticFiles
import json
import asyncio
from typing import List, Optional
from pydantic import BaseModel

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from app.downloader import DownloadManager
from app.database import SessionLocal, DatabaseError, get_all_downloads, update_download, delete_download, add_download  # Add missing import

def create_app():
    app = FastAPI()
    
    # Mount static files
    app.mount("/static", StaticFiles(directory="static"), name="static")
    
    # Initialize download manager
    @app.on_event("startup")
    async def startup_event():
        DownloadManager.check_list_status()
    
    return app

app = create_app()

class TaskCreate(BaseModel):
    url: str
    name: Optional[str] = None
    save_dir: str = "/downloads"  # 字段名与数据库表结构对齐
    format: str = "mp4"
    quality: str = "high"
    download_mode: str = "multithread"
    proxy: Optional[str] = None
    headers: Optional[str] = None

@app.get("/api/tasks")
async def get_tasks():
    """获取所有下载任务"""
    try:
        tasks = get_all_downloads()
        return {
            "status": "success", 
            "data": [{
                "id": task["id"],
                "name": task["name"],
                "dir": task["save_dir"],
                "status": task["status"],
                "progress": task["progress"],
                "speed": task["speed"],
                "size": task["size"],
                "createdtime": task["createdtime"],
                "message": task.get("message")
            } for task in tasks]
        }
    except DatabaseError as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/api/tasks")
async def create_task(task: TaskCreate):
    """创建下载任务"""
    try:
        for url_line in task.url.split('\n'):
            if not url_line.strip():
                continue
                
            # Replace ORM operation with database.py function
            task_id = add_download(
                url=url_line.strip(),
                name=task.name,
                save_dir=task.save_dir,
                format=task.format,
                quality=task.quality,
                download_mode=task.download_mode,
                proxy=task.proxy,
                headers=task.headers,
                status="pending"
            )
            
        return {"status": "success", "message": "Tasks created"}
    except DatabaseError as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/api/tasks/{task_id}/stop")
async def stop_task(task_id: int):
    """停止下载任务"""
    try:
        if update_download(task_id, status="stopped"):
            return {"status": "success", "message": "Task stopped"}
        raise HTTPException(status_code=404, detail="Task not found")
    except DatabaseError as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/api/tasks/{task_id}/resume")
async def resume_task(task_id: int):
    """恢复下载任务"""
    db = SessionLocal()
    try:
        db.begin()
        task = db.execute(
            "SELECT * FROM downloads WHERE id=:task_id FOR UPDATE", 
            {"task_id": task_id}
        ).fetchone()
        if not task:
            db.rollback()
            raise HTTPException(status_code=404, detail="Task not found")
        
        db.execute(
            "UPDATE downloads SET status='pending' WHERE id=:task_id",
            {"task_id": task_id}
        )
        db.commit()
        return {"status": "success", "message": "Task resumed"}
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"恢复任务失败: {str(e)}")
    finally:
        db.close()

@app.delete("/api/tasks/{task_id}")
async def delete_task(task_id: int):
    """删除下载任务"""
    try:
        # 先标记为deleted状态
        update_download(task_id, status="deleted")
        if delete_download(task_id):
            return {"status": "success", "message": "Task deleted"}
        raise HTTPException(status_code=404, detail="Task not found")
    except DatabaseError as e:
        raise HTTPException(status_code=500, detail=str(e))

from app.downloader import DownloadManager

@app.get("/api/sse")
async def sse_updates():
    """SSE实时更新"""
    async def event_generator():
        while True:
            try:
                tasks = get_all_downloads()  # Use database.py function
                data = [{
                    "id": task["id"],
                    "status": task["status"],
                    "progress": task["progress"],
                    "speed": task["speed"],
                    "size": task["size"]
                } for task in tasks]
                yield f"data: {json.dumps(data)}\n\n"
                await asyncio.sleep(1)
            except Exception as e:
                yield f"event: error\ndata: {json.dumps({'error': str(e)})}\n\n"

    return StreamingResponse(
        event_generator(),
        media_type="text/event-stream",
        headers={
            "Cache-Control": "no-cache",
            "Connection": "keep-alive"
        }
    )

# Replace ORM operations with database.py functions
task_id = add_download(
    url=url_line.strip(),
    name=task.name,
    save_dir=task.save_dir,
    format=task.format,
    quality=task.quality,
    download_mode=task.download_mode,
    proxy=task.proxy,
    headers=task.headers
)